package com.example.monitor.service.impl;

import com.example.monitor.exception.BusinessException;
import com.example.monitor.model.DO.SystemSetting;
import com.example.monitor.model.DTO.SystemSettingsDTO;
import com.example.monitor.model.VO.ResultVO;
import com.example.monitor.model.VO.SystemSettingsUpdateVO;
import com.example.monitor.model.VO.SystemSettingsVO;
import com.example.monitor.repository.SystemSettingsRepository;
import com.example.monitor.service.SystemSettingsService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
@RequiredArgsConstructor
public class SystemSettingsServiceImpl implements SystemSettingsService {

    private final SystemSettingsRepository settingsRepository;

    @Override
    @Transactional(readOnly = true)
    public ResultVO<SystemSettingsVO> getSystemSettings() {
        List<String> requiredKeys = Arrays.asList(
                "video_storage_duration",
                "save_frequency",
                "alarm_reminders",
                "log_storage_duration",
                "backup_frequency"
        );

        List<SystemSetting> settings = settingsRepository.findByKeys(requiredKeys);

        SystemSettingsVO vo = mapToVo(settings);

        return ResultVO.success("查询成功", vo);
    }

    @Override
    @Transactional
    public void updateSystemSettings(SystemSettingsUpdateVO updateVO) {
        try {
            // 验证并更新每个设置项
            updateSetting("video_storage_duration",
                    updateVO.getVideoStorageDuration().toString(),
                    "number");

            updateSetting("save_frequency",
                    updateVO.getSaveFrequency(),
                    "string");

            updateSetting("alarm_reminders",
                    String.join(",", updateVO.getAlarmReminders()),
                    "array");

            updateSetting("log_storage_duration",
                    updateVO.getLogStorageDuration().toString(),
                    "number");

            updateSetting("backup_frequency",
                    updateVO.getBackupFrequency(),
                    "string");

        } catch (Exception e) {
            throw new BusinessException("更新系统设置失败: " + e.getMessage());
        }
    }

    private void updateSetting(String key, String value, String expectedType) {
        // 1. 检查设置项是否存在
        SystemSetting setting = settingsRepository.findByKey(key)
                .orElseThrow(() -> new BusinessException("配置项不存在: " + key));

        // 2. 验证类型是否匹配
        if (!setting.getType().equals(expectedType)) {
            throw new BusinessException("配置项类型不匹配: " + key);
        }

        // 3. 特殊验证逻辑
        if ("alarm_reminders".equals(key) && value.isEmpty()) {
            throw new BusinessException("报警提醒方式不能为空");
        }

        // 4. 更新值
        setting.setValue(value);
        settingsRepository.save(setting);

        // 5. 记录审计日志（可选）
        //log.info("系统设置已更新 - {}: {}", key, value);
    }

    private SystemSettingsVO mapToVo(List<SystemSetting> settings) {
        SystemSettingsVO vo = new SystemSettingsVO();

        settings.forEach(setting -> {
            switch (setting.getKey()) {
                case "video_storage_duration":
                    vo.setVideoStorageDuration(parseInt(setting.getValue()));
                    break;
                case "save_frequency":
                    vo.setSaveFrequency(setting.getValue());
                    break;
                case "alarm_reminders":
                    vo.setAlarmReminders(parseList(setting.getValue()));
                    break;
                case "log_storage_duration":
                    vo.setLogStorageDuration(parseInt(setting.getValue()));
                    break;
                case "backup_frequency":
                    vo.setBackupFrequency(setting.getValue());
                    break;
            }
        });

        return vo;
    }

    private Integer parseInt(String value) {
        try {
            return Integer.parseInt(value);
        } catch (NumberFormatException e) {
            return null;
        }
    }

    private List<String> parseList(String value) {
        return Arrays.asList(value.split(","));
    }
}